package vip.xiaonuo.pay.core.config;

import cn.hutool.core.lang.Console;
import cn.hutool.extra.spring.SpringUtil;
import com.alipay.api.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import vip.xiaonuo.dev.api.DevConfigApi;

@Configuration
public class AliPayClientConfig {


    /**
     * 应用ID,收款账号就是appId对应的支付宝账号
     */
    private static final String SYS_PAY_ALI_APP_ID = "SYS_PAY_ALI_APP_ID";

    /**
     * 支付宝网关
     */
    private static final String SYS_PAY_ALI_GATEWAY_URL = "SYS_PAY_ALI_GATEWAY_URL";

    /**
     * 商户私钥，RSA2私钥
     */
    private static final String SYS_PAY_ALI_MERCHANT_PRIVATE_KEY = "SYS_PAY_ALI_MERCHANT_PRIVATE_KEY";

    /**
     * 支付宝公钥
     */
    private static final String SYS_PAY_ALI_PUBLIC_KEY = "SYS_PAY_ALI_PUBLIC_KEY";


    @Bean
    public AlipayClient alipayClient() throws AlipayApiException {
        DevConfigApi devConfigApi = SpringUtil.getBean(DevConfigApi.class);
        String appId = devConfigApi.getValueByKey(SYS_PAY_ALI_APP_ID);
        String gatewayUrl = devConfigApi.getValueByKey(SYS_PAY_ALI_GATEWAY_URL);
        String merchantPrivateKey = devConfigApi.getValueByKey(SYS_PAY_ALI_MERCHANT_PRIVATE_KEY);
        String publicKey = devConfigApi.getValueByKey(SYS_PAY_ALI_PUBLIC_KEY);

        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setAppId(appId);
        alipayConfig.setServerUrl(gatewayUrl);
        alipayConfig.setPrivateKey(merchantPrivateKey);
        alipayConfig.setAlipayPublicKey(publicKey);
        // 可选，仅支持JSON
        alipayConfig.setFormat(AlipayConstants.FORMAT_JSON);

        // 必选，请求使用的编码格式，如utf-8,gbk,gb2312等
        alipayConfig.setCharset(AlipayConstants.CHARSET_UTF8);

        // 必选，商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
        alipayConfig.setSignType(AlipayConstants.SIGN_TYPE_RSA2);

        return new DefaultAlipayClient(alipayConfig);
    }
}
